import websocket
import json

try:
    import thread
except ImportError:
    import _thread as thread
import time

ls = []


def on_message(ws, message):
    print(message)
    ls.append(message)


def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            message_0 = {
                "message": {
                    "user_input": "Hello %d" % i,
                    "test": 123,
                }
            }
            message = json.dumps(message_0)
            print(message)
            ws.send(message)
            # ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    # url = "ws://echo.websocket.org/"
    url = "ws://127.0.0.1:8000/ws/chat/1/"

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(url,
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)

    try:
        ws.run_forever()
    except BrokenPipeError as e:
        print(e)
        ws.close()

    ts: str = ls[0]

    dc = json.loads(ts)
    print(f"接收的json数据: {ts}, \n转为dict后: {dc}")
